let _Vue = null;
class LiteVueRouter {
    private routeMap: {};
    private options: any;
    private mode:'history'|'hash';
    private data: {};
    static install(Vue:any){
        if (LiteVueRouter.install.installed){
            return;
        }
        LiteVueRouter.install.installed = true;
        _Vue = Vue;
        _Vue.mixin({
            beforeCreate(){
                _Vue.prototype.$router = this.$options.router;
            }
        })
    }

    constructor(options:any) {
        this.options = options;
        this.data = _Vue.observable({
            current:"/"
        });
        this.mode = this.options.mode ?? 'history';
        this.routeMap = {};
        this.init();
    }

    createRouteMap(){
        this.routeMap = this.options.routes.map(route=>{
            const {path,component} = route;
            return {[path]:component}
        }).reduce((acc,cur)=>({...acc,...cur}),{})
    }

    init(){
        this.initComponent(_Vue)
        this.createRouteMap();
        this.initEvent();
    }

    initComponent(Vue: any){
        const self = this;
        Vue.component('router-link',{
            props:{
                to:String
            },
            render(h:any){
                const href = self.mode==='history'?this.to:`#${this.to}`
                return h('a',{attrs:{href},on:{
                    click:this.clickHandler
                    }},[this.$slots.default])
            },
            methods:{
                clickHandler(e:Event){
                    e.preventDefault();
                    const href = self.mode==="history"?this.to:`#${this.to}`
                    history.pushState({},'',href);
                    self.data.current = href;
                }
            }
        })
        Vue.component('router-view',{
            render:(h:any)=>{
                const link = this.mode==="history"?this.data.current:this.data.current.slice(1);
                const comp = this.routeMap[link];
                return h(comp)
            }
        })
    }

    initEvent(){
        window.addEventListener('popstate',()=>{
            const href = this.mode==='history'?location.pathname:location.hash;
            this.data.current = href;
        })
    }
}

export default LiteVueRouter;
